package com.gbr.client;

import javafx.application.Platform;

import org.osgi.framework.BundleContext;

import com.gbr.application.action.ShutdownAction;
import com.ng.framework.service.action.IActionListener;
import com.ng.framework.service.action.IActionService;
import com.ng.framework.service.log.ILogService;
import com.ng.framework.service.log.LogLevel;

public class ShutdownMonitor {
    private IActionService         actionService    = null;
    private ILogService            logService       = null;
    private BundleContext          bundleContext    = null;
    private ShutdownActionListener shutdownListener = new ShutdownActionListener();

    public final void activate(BundleContext b) {
        logService.log(getClass(), LogLevel.TRACE, "Activating");
        bundleContext = b;
        actionService.addListener(ShutdownAction.class, shutdownListener);
    }

    public final void deactivate() {
        logService.log(getClass(), LogLevel.TRACE, "Deactivating");
    }

    public final void bindService(IActionService service) {
        actionService = service;
    }

    public final void unbindService(IActionService service) {
        actionService = null;
    }

    public final void bindService(ILogService service) {
        logService = service;
    }

    public final void unbindService(ILogService service) {
        logService = null;
    }

    private void shutdown() {
        logService.log(getClass(), LogLevel.TRACE, "Shutting down the framework");
        try {
            bundleContext.getBundle(0).stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ShutdownActionListener implements IActionListener<ShutdownAction> {
        @Override
        public void actionPerformed(ShutdownAction action) {
            shutdown();
        }
    }
}
